package com.twb.auth.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.twb.auth.common.TwbLoginUser;
import com.twb.auth.dataScope.enums.DataScopeType;
import com.twb.auth.entity.twbApi.TwbApi;
import com.twb.auth.entity.twbAuth.vo.LoginUserVo;
import com.twb.auth.entity.twbOrganization.TwbOrganization;
import com.twb.auth.entity.twbProject.TwbProject;
import com.twb.auth.entity.twbResource.TwbResource;
import com.twb.auth.entity.twbRole.TwbRole;
import com.twb.auth.entity.twbTenantInfo.TwbTenantInfo;
import com.twb.auth.entity.twbUser.TwbUser;
import com.twb.auth.entity.twbUser.TwbUserOrganization;
import com.twb.auth.entity.twbUser.TwbUserRole;
import com.twb.auth.entity.twbUser.dto.GetTwbUserByIdDto;
import com.twb.auth.entity.twbUser.dto.SearchTwbUserDto;
import com.twb.auth.entity.twbUser.dto.TwbUserPostDto;
import com.twb.auth.entity.twbUser.dto.TwbUserRoleDto;
import com.twb.auth.entity.twbUser.vo.SaveTwbUserVo;
import com.twb.auth.entity.twbUser.vo.SearchTwbUserVo;
import com.twb.auth.entity.twbUser.vo.TwbUserPostVo;
import com.twb.auth.entity.twbUser.vo.TwbUserRoleVo;
import com.twb.auth.entity.twbUser.vo.UpdateTwbUserByIdVo;
import com.twb.auth.mapper.TwbUserMapper;
import com.twb.auth.service.ITwbApiService;
import com.twb.auth.service.ITwbOrganizationService;
import com.twb.auth.service.ITwbProjectService;
import com.twb.auth.service.ITwbResourceService;
import com.twb.auth.service.ITwbRoleService;
import com.twb.auth.service.ITwbTenantInfoService;
import com.twb.auth.service.ITwbUserPostService;
import com.twb.auth.service.ITwbUserService;
import com.twb.core.base.entity.BaseLoginUser;
import com.twb.core.base.entity.TwbPageInfo;
import com.twb.core.base.service.impl.BaseService;
import com.twb.core.cache.redis.RedisUtil;
import com.twb.core.constants.TwbConstants;
import com.twb.core.exception.ServiceException;
import com.twb.core.security.TwbSecurityProperties;
import com.twb.core.util.BeanUtils;
import com.twb.core.util.TwbPageUtil;
import com.twb.core.util.cipher.MD5Util;
import com.twb.system.common.SystemGlobal;

/**
 * @author DSY
 * @ClassName TwbUserService
 * @Description 用户管理service
 * @date 2018年11月25日 下午9:04:47
 */
@Service("twbUserService")
public class TwbUserService extends BaseService<TwbUserMapper, TwbUser> implements ITwbUserService {

	@Autowired
	TwbUserMapper twbUserMapper;
	@Autowired
	ITwbResourceService twbResourceService;
	@Autowired
	ITwbRoleService twbRoleService;
	@Autowired
	ITwbOrganizationService twbOrganizationService;
	@Autowired
	ITwbTenantInfoService twbTenantInfoService;
	@Autowired
	ITwbProjectService twbProjectService;
	@Autowired
	ITwbUserPostService twbUserPostService;
	@Autowired
	TwbSecurityProperties securityProperties;
	@Autowired
	RedisUtil redisUtil;
	@Autowired
	ITwbApiService twbApiService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public BaseLoginUser getLoginUserInfo(LoginUserVo vo) {
		TwbUser user = twbUserMapper.getUserByLoginName(vo.getLoginName());
		if (null == user) {
			throw new ServiceException("1001", "用户不存在");
		}
		String loginLock = SystemGlobal.sysConfig("login_lock");
		boolean openLock = false;
		//锁定时长
		long timeout = 5;
		//允许尝试次数
		int maxCount = 5;

		//判断是否开启锁定
		if (!StringUtils.isBlank(loginLock) && !loginLock.equals("off")) {
			String[] values = loginLock.split(":");
			timeout = Long.parseLong(values[0]);
			maxCount = Integer.parseInt(values[1]);
			openLock = true;
		}
		//判断账号是否已经锁定
		if(openLock) {
			boolean checklockLoginUser = twbSecurityUtil.checklockLoginUser(vo.getLoginName(), maxCount);
			if(checklockLoginUser) {
				throw new ServiceException("1003", "账号"+vo.getLoginName()+"已锁定，请"+timeout+"分钟后再试");
			}
		}
		
		String pwd = user.getPwd();
		if (!MD5Util.verify(vo.getPassword(), pwd)) {
			if (openLock) {
				//计算失败次数，达到锁定次数后，直接锁定账号
				boolean lockLoginUser = twbSecurityUtil.lockLoginUser(vo.getLoginName(), timeout, maxCount);
				if(lockLoginUser) {
					throw new ServiceException("1003", "账号"+vo.getLoginName()+"已锁定，请"+timeout+"分钟后再试");
				}
			}
			throw new ServiceException("1002", "密码错误");
		}
		//登录成功后，解锁用户
		if(openLock) {
			twbSecurityUtil.unlockLoginUser(vo.getLoginName());
		}

		// 绑定微信openid
		if (StringUtils.isNotBlank(vo.getOpenid())){
			TwbUser updateOpenid = new TwbUser();
			updateOpenid.setId(user.getId());
			updateOpenid.setOpenid(vo.getOpenid());
			this.setUpdateInfo(updateOpenid);
			twbUserMapper.updateById(updateOpenid);
		}

		// 绑定微信cpUserId
		if (StringUtils.isNotBlank(vo.getCpUserId())){
			TwbUser updateCpUserId = new TwbUser();
			updateCpUserId.setId(user.getId());
			updateCpUserId.setCpUserId(vo.getCpUserId());
			this.setUpdateInfo(updateCpUserId);
			twbUserMapper.updateById(updateCpUserId);
		}

		return getLoginUserInfoById(user.getId());
	}

	@Override
	public BaseLoginUser getLoginUserInfoById(String id) {
		TwbUser user = twbUserMapper.selectLoginUserById(id);
		if (null == user) {
			throw new ServiceException("1001", "用户不存在");
		}
		BaseLoginUser loginUser = new BaseLoginUser();
		BeanUtils.copyNotNullProperties(user, loginUser);

		if (user.getLoginName().equals(twbConfigProperties.getDeveloperName())) {
			loginUser.setDeveloper(true);
		} else {
			// 加载部门信息
			Set<TwbOrganization> orgs = twbOrganizationService.listOrganizationByUserId(id);
			if (CollectionUtils.isNotEmpty(orgs)) {
				TwbOrganization twbOrganization = orgs.iterator().next();
				loginUser.setOrgId(twbOrganization.getId());
				loginUser.setOrgCode(twbOrganization.getCode());
				loginUser.setOrgName(twbOrganization.getName());
				//保存公司信息
				TwbOrganization companyOrg = twbOrganizationService.getDeptOfCompanyOrgId(loginUser.getOrgId());
				if (companyOrg != null) {
					String companyOrgId = companyOrg.getId();
					String companyOrgCode = companyOrg.getCode();
					String companyOrgName = companyOrg.getName();
					loginUser.setCompanyOrgId(companyOrgId);
					loginUser.setCompanyOrgCode(companyOrgCode);
					loginUser.setCompanyOrgName(companyOrgName);
				}
			}
			// 获取用户最大数据权限类型
			String dataScopeType = twbUserMapper.getMaxDataScopeTypeById(loginUser.getId());
			loginUser.setDataScopeType(dataScopeType);
		}
		return loginUser;
	}

	@Override
	public GetTwbUserByIdDto getTwbUserById(String id) {
		TwbUser twbUser = getById(id);
		GetTwbUserByIdDto dto = new GetTwbUserByIdDto();
		BeanUtils.copyNotNullProperties(twbUser, dto);

		List<String> userOrgs = twbUserMapper.searchUserOrgByUserId(twbUser.getId());

		if (CollectionUtils.isNotEmpty(userOrgs)) {
			dto.setOrgId(userOrgs.get(0));

			String orgParentNames = twbOrganizationService.getOrgParentNames(dto.getOrgId());

			dto.setOrgParentNames(orgParentNames);
		}

		// 查询角色集合
		List<TwbUserRoleDto> userRoleList = twbUserMapper.searchUserRoleByUserId(twbUser.getId());
		dto.setRoles(userRoleList);

		// 查询岗位集合
		List<TwbUserPostDto> userPostList = twbUserMapper.searchUserPostByUserId(twbUser.getId());
		dto.setPosts(userPostList);

		return dto;
	}

	@Override
	public TwbPageInfo<SearchTwbUserDto> searchTwbUser(SearchTwbUserVo vo) {
		BaseLoginUser loginUser = getLoginUser();
		String parentId = vo.getOrgId();
		//如果parentId为空，则默认传递当前登录用户所属租户的组织机构ID
		if(StringUtils.isBlank(parentId)) {
			if (!loginUser.isDeveloper()) {
				String tenantId = loginUser.getTenantId();
				if (StringUtils.isNotBlank(tenantId)) {
					TwbTenantInfo tenantInfo = twbTenantInfoService.getById(tenantId);
					vo.setOrgId(tenantInfo.getOrgId());
				}
			}
		}

		if (StringUtils.isNotBlank(parentId) && vo.getIsAllChildNode()) {
			TwbOrganization twbOrganization = twbOrganizationService.getById(parentId);
			vo.setOrgSearchKey(twbOrganization.getSearchKey());
			vo.setOrgId(null);
		}
		vo.setDeveloperName(twbConfigProperties.getDeveloperName());//不显示developer到页面上
		TwbPageUtil.startPage(vo);
		List<SearchTwbUserDto> list = twbUserMapper.searchTwbUser(vo);
		return TwbPageUtil.of(list);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveTwbUser(SaveTwbUserVo vo) {
		TwbUser record = new TwbUser();
		record.setLoginName(vo.getLoginName());
		record.setIsdel(0);
		long count = this.count(record);
		if (count > 0) {
			throw new ServiceException(vo.getLoginName() + "已存在");
		}
		String phone = vo.getPhone();
		if (StringUtils.isNoneBlank(phone)) {
			record = new TwbUser();
			record.setPhone(vo.getPhone());
			record.setIsdel(0);
			count = this.count(record);
			if (count > 0) {
				throw new ServiceException(vo.getPhone() + "已存在");
			}
		}
		String mail = vo.getMail();
		if (StringUtils.isNotBlank(mail)) {
			record = new TwbUser();
			record.setMail(vo.getMail());
			record.setIsdel(0);
			count = this.count(record);
			if (count > 0) {
				throw new ServiceException(vo.getMail() + "已存在");
			}
		}
		// 保存用户对象
		record = new TwbUser();
		BeanUtils.copyNotNullProperties(vo, record);
		record.setId(getUUID());
		this.setCreateInfo(record);
		record.setFirstLogin(1);
		record.setStatus("1");
		record.setUpdateDate(LocalDateTime.now());

		String orgId = vo.getOrgId();
		if (StringUtils.isNotBlank(orgId)) {
			TwbOrganization twbOrganization = twbOrganizationService.getById(orgId);
			if (twbOrganization == null) {
				throw new ServiceException("组织机构信息不存在");
			}
			String tenantId = twbOrganization.getTenantId() == null ? TwbConstants.DEFAULT_TENANTID
					: twbOrganization.getTenantId();
			record.setTenantId(tenantId);
		}

		boolean result = this.save(record);

		// 保存用户机构信息
		if (result && StringUtils.isNotBlank(vo.getOrgId())) {
			this.saveUserOrg(record.getId(), vo.getOrgId());
		}

		// 保存用户角色
		if (result && CollectionUtils.isNotEmpty(vo.getRoles())) {
			List<String> roleIds = new ArrayList<>();
			for (TwbUserRoleVo role : vo.getRoles()) {
				roleIds.add(role.getRoleId());
			}
			this.saveUserRole(record.getId(), String.join(",", roleIds));
		}

		// 保存用户岗位
		if (result && CollectionUtils.isNotEmpty(vo.getPosts())) {
			this.saveUserPost(record.getId(), vo.getPosts());
		}

		return result;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateTwbUserById(UpdateTwbUserByIdVo vo) {
		TwbUser record = this.getById(vo.getId());
		if (null == record) {
			throw new ServiceException("用户不存在");
		}

		TwbUser checkVo = new TwbUser();
		if (vo.getLoginName() != null && !record.getLoginName().equals(vo.getLoginName())) {
			checkVo.setLoginName(vo.getLoginName());
			checkVo.setIsdel(0);
			long count = this.count(checkVo);
			if (count > 0) {
				throw new ServiceException(vo.getLoginName() + "已存在");
			}
		}

		String phone = vo.getPhone();
		if (StringUtils.isNoneBlank(phone) && !vo.getPhone().equals(record.getPhone())) {
			checkVo = new TwbUser();
			checkVo.setPhone(vo.getPhone());
			checkVo.setIsdel(0);
			long count = this.count(checkVo);
			if (count > 0) {
				throw new ServiceException(vo.getPhone() + "已存在");
			}
		}

		String mail = vo.getMail();
		if (StringUtils.isNotBlank(mail) && !vo.getMail().equals(record.getMail())) {
			checkVo = new TwbUser();
			checkVo.setMail(vo.getMail());
			checkVo.setIsdel(0);
			long count = this.count(checkVo);
			if (count > 0) {
				throw new ServiceException(vo.getMail() + "已存在");
			}
		}

		String orgId = vo.getOrgId();
		if (StringUtils.isNotBlank(orgId)) {
			TwbOrganization twbOrganization = twbOrganizationService.getById(orgId);
			if (twbOrganization == null) {
				throw new ServiceException("组织机构信息不存在");
			}

			String tenantId = twbOrganization.getTenantId() == null ? TwbConstants.DEFAULT_TENANTID
					: twbOrganization.getTenantId();
			record.setTenantId(tenantId);
		}

		BeanUtils.copyProperties(vo, record);
		this.setUpdateInfo(record);
		boolean result = this.updateById(record);

		// 保存用户机构信息
		if (result && StringUtils.isNotBlank(vo.getOrgId())) {
			this.saveUserOrg(record.getId(), vo.getOrgId());
		}

		// 保存用户角色
		if (result && CollectionUtils.isNotEmpty(vo.getRoles())) {
			List<String> roleIds = new ArrayList<>();
			for (TwbUserRoleVo role : vo.getRoles()) {
				roleIds.add(role.getRoleId());
			}
			this.saveUserRole(record.getId(), String.join(",", roleIds));
		}

		// 保存用户岗位
		if (result && CollectionUtils.isNotEmpty(vo.getPosts())) {
			this.saveUserPost(record.getId(), vo.getPosts());
		}

		return result;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean deleteTwbUserById(String id) {
		// 删除用户机构信息
		twbUserMapper.deleteUserOrgByUserId(id);
		// 删除用户角色信息
		twbUserMapper.deleteUserRoleByUserId(id);
		// 删除用户岗位信息
		twbUserMapper.deleteUserPostByUserId(id);
		// 删除用户信息
		return this.removeById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int saveUserOrg(String userId, String orgIds) {
		TwbUser user = this.getById(userId);
		if (user == null) {
			throw new ServiceException("用户" + user + "未找到");
		}
		twbUserMapper.deleteUserOrgByUserId(userId);
		String[] ids = orgIds.split(",");
		int result = 0;
		List<TwbOrganization> orgs = twbOrganizationService.listByIds(Arrays.asList(ids));
		for (TwbOrganization org : orgs) {
			TwbUserOrganization userOrganization = new TwbUserOrganization();
			userOrganization.setUserId(userId);
			userOrganization.setOrgId(org.getId());
			result = result + twbUserMapper.saveUserOrg(userOrganization);
		}
		return result;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public int saveUserRole(String userId, String roleIds) {
		TwbUser user = this.getById(userId);
		if (user == null) {
			throw new ServiceException("用户" + user + "未找到");
		}
		int result = 0;
		result = twbUserMapper.deleteUserRoleByUserId(userId);
		if (StringUtils.isNotBlank(roleIds)) {
			String[] ids = roleIds.split(",");
			List<TwbRole> roles = twbRoleService.listByIds(Arrays.asList(ids));
			for (TwbRole twbRole : roles) {
				TwbUserRole userRole = new TwbUserRole();
				userRole.setUserId(userId);
				userRole.setRoleId(twbRole.getId());
				result = result + twbUserMapper.saveUserRole(userRole);
			}
		}

		return result;
	}

	/**
	 * 保存用户岗位
	 * @param userId
	 * @param posts
	 * @return
	 */
	private int saveUserPost(String userId, List<TwbUserPostVo> posts) {
		TwbUser user = this.getById(userId);
		if (user == null) {
			throw new ServiceException("用户" + user + "未找到");
		}
		int result = 0;
		twbUserMapper.deleteUserPostByUserId(userId);

		for (TwbUserPostVo post : posts) {
			post.setId(getUUID());
			post.setUserId(user.getId());
			result = result + twbUserMapper.saveUserPost(post);
		}

		return result;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateCurrentPwd(String userId, String pwd) {
		TwbUser user = this.getById(userId);
		if (user == null) {
			throw new ServiceException("用户" + user + "未找到");
		}

		user.setPwd(MD5Util.generate(pwd));
		user.setId(userId);
		this.setUpdateInfo(user);
		return this.updateById(user);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateUserPwd(String userId, String password) {
		TwbUser user = this.getById(userId);
		if (user == null) {
			throw new ServiceException("用户" + user + "未找到");
		}
		user.setPwd(MD5Util.generate(password));
		user.setId(userId);
		this.setUpdateInfo(user);

		user.setFirstLogin(0);

		return this.updateById(user);
	}

	@Override
	public TwbPageInfo<SearchTwbUserDto> searchRoleSelectUsers(SearchTwbUserVo vo) {
		TwbPageUtil.startPage(vo);
		List<SearchTwbUserDto> list = twbUserMapper.searchRoleSelectUsers(vo);
		return TwbPageUtil.of(list);
	}

	@Override
	public TwbPageInfo<SearchTwbUserDto> searchRoleUsers(SearchTwbUserVo vo) {
		TwbPageUtil.startPage(vo);
		List<SearchTwbUserDto> list = twbUserMapper.searchRoleUsers(vo);
		return TwbPageUtil.of(list);
	}

	@Override
	public boolean logicDeleteTwbUserById(String ids) {

		for (String id : ids.split(",")) {
			TwbUser record = this.getById(id);
			if (null == record) {
				throw new ServiceException("用户信息不存在");
			}

			// 删除用户机构信息
			twbUserMapper.deleteUserOrgByUserId(id);
			// 删除用户角色信息
			twbUserMapper.deleteUserRoleByUserId(id);

			setUpdateInfo(record);
			record.setIsdel(1);
			updateById(record);
		}

		return true;
	}

	@Override
	public int grantOrganization(String orgId, String userId) {
		TwbUser u = new TwbUser();
		u.setId(userId);
		u.setIsdel(0);
		long count = this.count(u);
		if (count <= 0) {
			throw new ServiceException("用户信息不存在");
		}
		TwbOrganization o = new TwbOrganization();
		o.setId(orgId);
		o.setIsdel(0);
		count = twbOrganizationService.count(o);
		if (count <= 0) {
			throw new ServiceException("组织机构信息不存在");
		}
		return twbUserMapper.grantOrganization(orgId, userId);
	}

	@Override
	public String getUserNameByLoginName(String loginName) {
		TwbUser user = twbUserMapper.getUserByLoginName(loginName);
		if (user == null) {
			return "";
		}
		return user.getName();
	}

	@Override
	public void cacheLoginUserApis(BaseLoginUser loginUser, Long timeoutSeconds) {
		List<TwbApi> list = new ArrayList<TwbApi>();
		if (loginUser.isDeveloper()) {
			TwbApi record = new TwbApi();
			record.setIsdel(0);
			list = twbApiService.list(record);
		}else {
			List<String> resIds = new ArrayList<>();
			TwbLoginUser twbLoginUser = twbSecurityUtil.getTwbLoginUser(loginUser.getToken());
			twbLoginUser.getResources().forEach(item -> {
				if(StringUtils.isNotBlank(item.getParentResId()) && !resIds.contains(item.getParentResId())){
					resIds.add(item.getParentResId());
				}
			});

			list = twbUserMapper.listApisByUserId(loginUser.getId(), resIds);
		}
		if (!list.isEmpty()) {
			Map<String, TwbApi> map = new HashMap<String, TwbApi>();
			for (TwbApi twbApi : list) {
				map.put(twbApi.getUrl(), twbApi);
			}
			String key = this.twbConfigProperties.getLoginApiRedisKey(loginUser.getToken());
			redisUtil.getRedisTemplate().opsForHash().putAll(key, map);
		}
	}

	@Override
	public List<TwbResource> listLoginUserResources(BaseLoginUser loginUser, String appId) {
		// 加载用户资源信息，如果是developer，则加载所有资源
		List<TwbResource> resources = null;
		if (loginUser.isDeveloper()) {
			resources = twbResourceService.listResourceAll(appId);
		} else {
			String userId = loginUser.getId();
			// 加载用户资源信息
			resources = twbResourceService.listResourceByUserId(userId, appId);
		}
		// 资源去重后排序(这里包含了当前用户当前系统可访问的所有资源)
		// 去重
		resources = resources.stream()
				.collect(Collectors.collectingAndThen(
						Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TwbResource::getId))),
						ArrayList::new));
		// 排序
		new TwbResource().sort(resources);
		return resources;
	}

	@Override
	public Set<String> cacheLoginUserDataScope(BaseLoginUser loginUser, Long timeoutSeconds) {
		/*
		 * 1.先获取角色的最大数据权限 2.获取所有角色的自定义数据权限
		 */
		Set<String> dataScopes = new HashSet<>();
		String dataScopeType = loginUser.getDataScopeType();
		// 如果是全部数据，则不获取数据权限
		if (dataScopeType == null || dataScopeType.equals(DataScopeType.ALL.getCode())) {
			return null;
		}
		if (dataScopeType.equals(DataScopeType.ORG.getCode())) {
			TwbOrganization companyOrg = twbOrganizationService.getById(loginUser.getCompanyOrgId());
			if (companyOrg != null) {
				String companyOrgId = companyOrg.getId();
				dataScopes.add(companyOrgId);
			}
		} else if (dataScopeType.equals(DataScopeType.ORG_WITH_CHILD.getCode())) {
			TwbOrganization companyOrg = twbOrganizationService.getById(loginUser.getCompanyOrgId());
			if (companyOrg != null) {
				String companyOrgId = companyOrg.getId();
				dataScopes.add(companyOrgId);
				List<String> childrenOrgIds = twbOrganizationService.listChildrenOrgIds(companyOrgId);
				dataScopes.addAll(childrenOrgIds);
			}
		} else if (dataScopeType.equals(DataScopeType.DEPT.getCode())) {
			// 如果是本部门，则添加用户所在部门ID
			dataScopes.add(loginUser.getOrgId());
		} else if (dataScopeType.equals(DataScopeType.DEPT_WITH_CHILD.getCode())) {
			// 如果是本部门及子部门，则添加本部门及子部门ID
			List<String> orgIds = twbOrganizationService.listChildrenOrgIds(loginUser.getOrgId());
			dataScopes.addAll(orgIds);
			dataScopes.add(loginUser.getOrgId());
		}
		// 添加自定义数据权限
		List<String> defineDataScopes = twbUserMapper.listDataScopesById(loginUser.getId());
		if (!defineDataScopes.isEmpty()) {
			dataScopes.addAll(defineDataScopes);
		}
		// 缓存用户数据权限信息
		String key = this.twbConfigProperties.getLoginDataScopeRedisKey(loginUser.getToken());
		redisUtil.set(key, dataScopes, timeoutSeconds, TimeUnit.SECONDS);
		return dataScopes;
	}

	@Override
	public TwbLoginUser cacheTwbLoginUserInfo(String appId, BaseLoginUser baseLoginUser, Long timeoutSeconds) {
		TwbLoginUser user = new TwbLoginUser();

		BeanUtils.copyNotNullProperties(baseLoginUser, user);
		user.setToken(baseLoginUser.getToken());
		user.setIp(baseLoginUser.getIp());

		// 用户可访问系统
		List<TwbProject> projectList = new ArrayList<>();
		if (user.isDeveloper()) {
			projectList = twbProjectService.getRedisProject().stream().filter(pro->"1".equals(pro.getAppType())).collect(Collectors.toList());
		} else {
			projectList = twbProjectService.searchProjectsByLoginUser(user).stream().filter(pro->"1".equals(pro.getAppType())).collect(Collectors.toList());
		}
		user.setAppList(projectList);
		if (CollectionUtils.isNotEmpty(projectList) && appId != null) {
			for (TwbProject twbProject : projectList) {
				if (twbProject.getAppId().equalsIgnoreCase(appId)) {
					user.setApp(twbProject);
					break;
				}
			}
			// 如果当前登录用户传的APPID没有访问权限，则默认给第一个项目的访问权限
			if (user.getApp() == null) {
				user.setApp(projectList.get(0));
				appId = user.getApp().getId();
			}
		}
		// 缓存用户资源菜单权限
		List<TwbResource> resources = listLoginUserResources(user, appId);
		user.setResources(resources);

		if (!user.isDeveloper()) {
			String userId = user.getId();

			// 加载用户角色信息
			Set<TwbRole> roles = twbRoleService.listRoleByUserId(userId);
			user.setRoles(roles);
			// 加载部门信息
			Set<TwbOrganization> orgs = twbOrganizationService.listOrganizationByUserId(userId);
			user.setOrganizations(orgs);

			if (CollectionUtils.isNotEmpty(orgs)) {
				user.setOrgId(orgs.iterator().next().getId());
			}
			// 加载租户信息
			String tenantId = user.getTenantId();
			if (StringUtils.isNotEmpty(tenantId)) {
				TwbTenantInfo tenantInfo = twbTenantInfoService.getById(user.getTenantId());
				user.setTenantInfo(tenantInfo);
			}

			// 查询岗位集合
			List<TwbUserPostDto> userPostList = twbUserMapper.searchUserPostByUserId(userId);
			user.setPosts(userPostList);

		}

		// 缓存用户信息
		String key = this.twbConfigProperties.getTwbLoginRedisKey(user.getToken());
		redisUtil.set(key, user, timeoutSeconds, TimeUnit.SECONDS);
		return user;
	}

	@Override
	public List<SearchTwbUserDto> searchUsersList(SearchTwbUserVo vo) {
		vo.setStatus("1");
		return twbUserMapper.searchTwbUser(vo);
	}

	@Override
	public TwbUser getUserByOpenId(String openid) {
		return twbUserMapper.searchUserByOpenId(openid);
	}

	@Override
	public TwbUser getUserByCpUserId(String cpUserId) {
		return twbUserMapper.searchUserByCpUserId(cpUserId);
	}

	@Override
	public List<TwbUser> listByPostIdAndOrgId(String postId, String orgId) {
		// TODO Auto-generated method stub
		return twbUserMapper.listByPostIdAndOrgId(postId,orgId);
	}

	@Override
	public TwbUser getDirectSupervisorById(String id) {
		// TODO Auto-generated method stub
		return twbUserMapper.getDirectSupervisorById(id);
	}


}
